package com.woyou.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.jing.biandang.R;
import com.woyou.activity.LoginActivity;
import com.woyou.activity.WelcomeActivity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

public class DownloadeManager {
	private boolean isFinish = false;
	public WelcomeActivity welcomeActivity;
	public LoginActivity loginActivity;
	private Activity activity;
	private String apkUrl;
	private String apkNames = "ShopClient.apk";
	private Dialog downloadDialog;
	/* 下载包安装路径 */
	private String savePath = "";
	private String saveFileName = "";
	/* 进度条与通知ui刷新的handler和msg常量 */
	private ProgressBar checkupdate_progress;

	private static final int DOWN_UPDATE = 1;
	private static final int DOWN_OVER = 2;
	private int progress;
	private Thread downLoadThread;
	private boolean interceptFlag = false;
	public boolean isdown = false;
	private int apkLength;
	private int apkCurrentDownload;

	private RelativeLayout checkupdate_loading;
	private LinearLayout checkupdate_error;

	/**
	 * 上下文，更新的url，是否
	 * 
	 * @param mContext
	 * @param apkUrl
	 */
	public DownloadeManager(Activity activity, String apkUrl) {
		this.activity = activity;
		this.apkUrl = apkUrl;
		this.savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator
				+ "Android/data/com.jing.biandang/apk/";
		this.saveFileName = savePath + apkNames;
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWN_UPDATE:
				checkupdate_progress.setProgress(progress);
				break;
			case DOWN_OVER:
				installApk();
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 显示下载对话框 判断是否要关闭当前的activity
	 * 
	 * @param isFinish
	 */
	public void showDownloadDialog(boolean isFinish) {
		this.isFinish = isFinish;
		downloadDialog = new Dialog(activity, R.style.defaultDialogStyle);
		View view = LayoutInflater.from(activity).inflate(R.layout.layout_update, null);
		checkupdate_progress = (ProgressBar) view.findViewById(R.id.layout_checkupdate_progress);
		RelativeLayout checkupdate_cancel = (RelativeLayout) view.findViewById(R.id.layout_checkupdate_cancel);
		downloadDialog.setContentView(view);
		downloadDialog.setCanceledOnTouchOutside(false);
		downloadDialog.show();
		checkupdate_cancel.setOnClickListener(new android.view.View.OnClickListener() {
			@Override
			public void onClick(View v) {
				downloadDialog.dismiss();
				interceptFlag = true;
			}
		});
		downloadApk();
	}

	/**
	 * 显示下载对话框 WelcomeActivity 用于登录是检测更新
	 * 
	 * @param isFinish
	 */
	public void showDownloadDialog(final WelcomeActivity welcomeActivity, boolean isFinish) {
		this.welcomeActivity = welcomeActivity;
		this.isFinish = isFinish;
		downloadDialog = new Dialog(activity, R.style.defaultDialogStyle);
		View view = LayoutInflater.from(activity).inflate(R.layout.layout_update, null);
		checkupdate_progress = (ProgressBar) view.findViewById(R.id.layout_checkupdate_progress);

		checkupdate_loading = (RelativeLayout) view.findViewById(R.id.layout_checkupdate_loading);
		checkupdate_error = (LinearLayout) view.findViewById(R.id.layout_checkupdate_error);

		RelativeLayout checkupdate_giveup = (RelativeLayout) view.findViewById(R.id.layout_checkupdate_giveup);
		RelativeLayout checkupdate_tryagain = (RelativeLayout) view.findViewById(R.id.layout_checkupdate_tryagain);
		RelativeLayout checkupdate_cancel = (RelativeLayout) view.findViewById(R.id.layout_checkupdate_cancel);
		downloadDialog.setContentView(view);
		downloadDialog.setCanceledOnTouchOutside(false);
		downloadDialog.show();
		checkupdate_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				downloadDialog.dismiss();
				interceptFlag = true;
				welcomeActivity.welcomeController.jump2Home();
			}
		});
		checkupdate_giveup.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				downloadDialog.dismiss();
				interceptFlag = true;
				welcomeActivity.welcomeController.jump2Home();
			}
		});
		checkupdate_tryagain.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				interceptFlag = true;
				switchView(true);
				downloadApk();
			}
		});
		downloadApk();
	}

	/**
	 * 显示下载对话框 LoginActivity 用于登录是检测更新
	 * 
	 * @param isFinish
	 */
	public void showDownloadDialog(final LoginActivity loginActivity, boolean isFinish) {
		this.loginActivity = loginActivity;
		this.isFinish = isFinish;
		downloadDialog = new Dialog(activity, R.style.defaultDialogStyle);
		View view = LayoutInflater.from(activity).inflate(R.layout.layout_update, null);
		checkupdate_progress = (ProgressBar) view.findViewById(R.id.layout_checkupdate_progress);
		checkupdate_loading = (RelativeLayout) view.findViewById(R.id.layout_checkupdate_loading);
		checkupdate_error = (LinearLayout) view.findViewById(R.id.layout_checkupdate_error);
		RelativeLayout checkupdate_giveup = (RelativeLayout) view.findViewById(R.id.layout_checkupdate_giveup);
		RelativeLayout checkupdate_tryagain = (RelativeLayout) view.findViewById(R.id.layout_checkupdate_tryagain);
		RelativeLayout checkupdate_cancel = (RelativeLayout) view.findViewById(R.id.layout_checkupdate_cancel);
		downloadDialog.setContentView(view);
		downloadDialog.setCanceledOnTouchOutside(false);
		downloadDialog.show();

		checkupdate_cancel.setOnClickListener(new android.view.View.OnClickListener() {
			@Override
			public void onClick(View v) {
				downloadDialog.dismiss();
				interceptFlag = true;
				loginActivity.loginController.jump2Home();
			}
		});
		checkupdate_giveup.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				downloadDialog.dismiss();
				interceptFlag = true;
				loginActivity.loginController.jump2Home();
			}
		});
		checkupdate_tryagain.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				interceptFlag = true;
				switchView(true);
				downloadApk();
			}
		});
		downloadApk();
	}

	private Runnable mdownApkRunnable = new Runnable() {
		@Override
		public void run() {
			try {
				File file = new File(savePath);
				if (!file.exists()) {
					file.mkdirs();
				}
				String apkFile = saveFileName;
				File ApkFile = new File(apkFile);
				FileOutputStream fos = new FileOutputStream(ApkFile);
				URL url = new URL(apkUrl);
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setConnectTimeout(30000);
				conn.setReadTimeout(30000);
				conn.connect();
				apkLength = conn.getContentLength();
				System.out.println();
				InputStream is = conn.getInputStream();
				apkCurrentDownload = 0;
				byte buf[] = new byte[1024];
				int length = -1;
				while ((length = is.read(buf)) != -1) {
					apkCurrentDownload += length;
					progress = (int) (((float) apkCurrentDownload / apkLength) * 100);
					// 更新进度
					mHandler.sendEmptyMessage(DOWN_UPDATE);
					fos.write(buf, 0, length);
					if (apkCurrentDownload == apkLength) {
						// 下载完成通知安装
						mHandler.sendEmptyMessage(DOWN_OVER);
						break;
					}
					if (interceptFlag) {
						ApkFile.delete();
						break;
					}
				}
				fos.close();
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
				switchView(false);
			}
		}
	};

	/**
	 * 切换下载页和下载错误页面
	 * 
	 * @param isLoading
	 *            true:显示下载页,隐藏错误页 false:隐藏下载页，显示错误页
	 */
	public void switchView(final boolean isLoading) {
		activity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (isLoading) {
					checkupdate_loading.setVisibility(View.VISIBLE);
					checkupdate_error.setVisibility(View.GONE);
				} else {
					checkupdate_loading.setVisibility(View.GONE);
					checkupdate_error.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	/**
	 * 下载apk
	 * 
	 * @param
	 */

	private void downloadApk() {
		downLoadThread = new Thread(mdownApkRunnable);
		downLoadThread.start();
	}

	/**
	 * 安装apk
	 * 
	 * @param
	 */
	private void installApk() {
		File apkfile = new File(saveFileName);
		if (!apkfile.exists()) {
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
		activity.startActivity(i);
		try {
			if (downloadDialog != null && downloadDialog.isShowing()) {
				downloadDialog.dismiss();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (isFinish) {
				if (welcomeActivity != null) {
					welcomeActivity.finish();
				} else if (loginActivity != null) {
					loginActivity.finish();
				}
			}
		}
	}
}
